<template>
  <el-card>
    <div slot="header">
      <span>{{ title }}</span>
    </div>
    <el-row v-if="!supplierId && !processBillId">
      <el-col :span="12">
        <el-form
          class="table_form_wrap"
          ref="supplierInfoForm"
          :model="supplierInfoForm"
          label-width="85px"
        >
          <el-form-item label="供应商代码" prop="supplierCode">
            <el-input
              v-model.trim="supplierInfoForm.supplierCode"
              placeholder="请选择供应商代码"
              readonly
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="showSupplierDialog"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <skus-table
      :showSelectCol="false"
      :showPagination="false"
      :columns="tableColumn"
      :dataSource="freightBillDTOList"
      :tableHeight="400"
      @handleCancelSelect="handleCancelSelect"
      @handleSelectChange="handleSelectChange"
    >
      <div slot="content_context" style="margin-bottom: 5px">
        <el-button v-show="supplierInfoForm.supplierCode" size="mini" type="primary" @click="handleAddRow"
          >添加行</el-button
        >
      </div>
    </skus-table>
    <el-row type="flex" justify="center" class="page-footer">
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit(true)">提交</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit(false)">暂存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-row>
    <!-- <SelectSupplierDialog
      :supplierVisible.sync="dialogVisible"
      @handle-select="handleGetSupplierInfo"
    /> -->
    <SelectUnitDialog
      :unitVisible.sync="unitVisible"
      @handle-select="handleGetUnitInfo"
    />
    <SelecFleetDialog
      :fleetVisible.sync="fleetVisible"
      @handle-select="handleGetFleetInfo"
    />
    <SelecFleetDialog
      :fleetVisible.sync="dialogVisible"
      @handle-select="handleGetSupplierInfo"
    />
  </el-card>
</template>
<script>
import SelectSupplierDialog from '@/pages/supplier/components/SelectSupplierDialog';
import SelectUnitDialog from '@/pages/supplier/components/selectUnitDialog';
import SelecFleetDialog from './components/SelectFleetDialog';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import SkusTable from '@/components/skusTable';
import { SHIPPING_STATUS_SELECT_LIST } from '@/pages/supplier/constants/common';
import {
  queryFreighDetailService,
  queryFreighDetailByProcessBillIdService,
  addFreightService,
  editFreightService,
  stashAddFreightService,
  editStashFreightService
} from '@api/supplier/management/freight';
import { queryManageAreaService } from '@api/supplier/components';

export default {
  components: {
    SkusTable,
    SelectSupplierDialog,
    SelectUnitDialog,
    SelecFleetDialog
  },
  data () {
    return {
      supplierId: null,
      processBillId: null,
      selectIndex: null,
      key: 1,
      tableColumn: [],
      submitLoading: false,
      dialogVisible: false,
      fleetVisible: false,
      unitVisible: false,
      areaOptions: [], // 所属区域下拉集合
      freightBillDTOList: [], // 表格数据
      supplierInfoForm: {
        supplierCode: '',
        supplierName: '',
        supplierId: '',
        freightPayer: '',
      }
    };
  },
  computed: {
    title () {
      return this.supplierId ? '修改运费' : '新建运费';
    },
  },
  created () {
    this.queryAreaList()
    const { supplierId, processId } = this.$route.query;
    this.supplierId = supplierId;
    this.processBillId = processId;
    if (supplierId) {
      this.getDetailData();
    }
    if (processId) {
      this.getDetailDataByProcessBillId();
    }
  },
  methods: {
    // 初始化表列
    initTableCloumn () {
      this.tableColumn = [
        { key: 'supplierCode', title: '供应商代码', width: 90 },
        { key: 'supplierName', title: '供应商名称', width: 90 },
        {
          key: 'fleetName',
          title: '供货车队',
          width: 150,
          render: (h, { row, index }) => {
            if (row.freightPayer == 40357) {
              return (
                <el-input
                  prefix-icon="el-icon-search"
                  readonly
                  value={ row.fleetName }
                  onFocus={ () => { this.showFleetDialog(index) } }
                />
              )
            }
            return (
              <el-input
                readonly
                value={ row.fleetName }
              />
            )
          }
        },
        {
          key: 'areaId',
          title: '所属区域',
          width: 150,
          type: 'selectChange',
          options: this.areaOptions
        },
        { key: 'freightType', title: '运费类型', width: 150, type: 'inputNoLimit', maxlength: 100 },
        {
          key: 'unitName',
          title: '计量单位',
          width: 150,
          render: (h, { row, index }) => {
            return (
              <el-input
                prefix-icon="el-icon-search"
                readonly
                value={ row.unitName }
                onFocus={ () => { this.showUnitDialog(index) } }
              />
            )
          }
        },
        { key: 'price', title: '单价（元）', width: 160, type: 'inputNumSpecial', precision: 3 },
        { key: 'floatRatio', title: '浮动比例', width: 160, type: 'inputNumSpecial', precision: 3 },
        { key: 'description', title: '运费描述', width: 180, type: 'inputNoLimit', maxlength: 100 },
        {
          key: 'enabled',
          title: '是否启用',
          width: 150,
          type: 'select',
          options: SHIPPING_STATUS_SELECT_LIST
        },
        { key: 'remark', title: '备注', type: 'inputNoLimit', maxlength: 100, width: 150 },
        { key: 'action', title: '操作', fixd: 'right' },
      ];
    },
    /* 删除按钮事件 */
    handleCancelSelect ({ row, index }) {
      this.freightBillDTOList.splice(index, 1);
    },
    // 选择所属区域
    handleSelectChange ({ row, val }) {
      row.areaName = this.areaOptions.find(item => item.manageAreaId == val).manageAreaName
    },
    // 显示供应商弹框
    showSupplierDialog () {
      this.dialogVisible = true;
    },
    // 显示计量单位弹框
    showUnitDialog (index) {
      this.selectIndex = index;
      this.unitVisible = true;
    },
    // 显示车队
    showFleetDialog (index) {
      this.selectIndex = index;
      this.fleetVisible = true;
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
    // 获取所属区域下拉集合
    queryAreaList () {
      queryManageAreaService().then((res) => {
        const { result } = res;
        result.forEach(item => {
          item.label = item.manageAreaName
          item.value = Number(item.manageAreaId)
        });
        this.areaOptions = result.filter((item) => item.manageAreaName !== '集团总部');
        this.initTableCloumn()
      })
    },
    // 选择车队
    handleGetFleetInfo (row) {
      const { supplierId, supplierName } = row;
      this.freightBillDTOList[this.selectIndex].fleetName = supplierName;
      this.freightBillDTOList[this.selectIndex].fleetId = supplierId;
    },
    // 选择计量单位
    handleGetUnitInfo (row) {
      const { unitName, uuid } = row;
      this.freightBillDTOList[this.selectIndex].unitName = unitName;
      this.freightBillDTOList[this.selectIndex].unitId = uuid;
    },
    // 获取供应商信息
    // 40357 我司承担
    // 40358 供应商承担
    // 40359 无运费
    handleGetSupplierInfo (row) {
      if (!row.freightPayer || row.freightPayer == 40359) {
        return this.$message.warning('无运费承担方')
      }
      this.freightBillDTOList = [];
      const {
        supplierCode, // 供应商编码
        supplierName, // 供应商名称
        supplierId, // 供应商id
        freightPayer, // 运费承担方
      } = row;
      if (row.freightPayer == 40358) {
        this.supplierInfoForm = {
          supplierCode,
          supplierName,
          supplierId,
          freightPayer,
          fleetId: supplierId,
          fleetName: supplierName,
        };
      }
      if (row.freightPayer == 40357) {
        this.supplierInfoForm = {
          supplierCode,
          supplierName,
          supplierId,
          freightPayer,
          fleetId: '',
          fleetName: '',
        };
      }
      this.handleAddRow()
    },
    // 获取详情
    getDetailData () {
      queryFreighDetailService({ supplierId: this.supplierId }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          this.freightBillDTOList = result.map(item => item)
        }
      });
    },
    // 获取详情 通过单据id
    getDetailDataByProcessBillId () {
      queryFreighDetailByProcessBillIdService({ processBillId: this.processBillId }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          this.freightBillDTOList = result.map(item => item)
        }
      });
    },
    // 添加行
    handleAddRow () {
      this.freightBillDTOList.push({
        key: this.key++,
        processBillId: '',
        supplierCode: '',
        supplierId: '',
        supplierName: '',
        fleetId: '',
        fleetName: '',
        areaId: '',
        areaName: '',
        freightType: '',
        unitId: '',
        unitName: '',
        price: '',
        floatRatio: '',
        description: '',
        enabled: 1, // 0:否 1:是
        enabledName: '',
        remark: '',
        ...this.supplierInfoForm
      })
    },
    // 提交
    handleSubmit (isSubmit) {
      if (!this.freightBillDTOList.length) {
        return this.$message.warning('请添加运费')
      }
      let hasEmptyVaule = this.freightBillDTOList.some((item) => (
        item.supplierCode == '' || item.fleetId == '' || item.areaId == '' || item.freightType == '' ||
        item.unitId == '' || item.price == '' || item.floatRatio == '' || item.description == ''
      ))
      if (hasEmptyVaule) {
        return this.$message.warning('运费信息填写不完整')
      }
      this.submitLoading = true;
      if (this.supplierId || this.processBillId) {
        if (isSubmit) {
          editFreightService(this.freightBillDTOList).then((res) => {
            this.submitLoading = true;
            if (isResponseSuccess(res)) {
              this.$message.success(res.message);
              this.handleCancel();
            }
          }).catch(() => {
            this.submitLoading = false;
          });
        } else {
          editStashFreightService(this.freightBillDTOList).then((res) => {
            this.submitLoading = true;
            if (isResponseSuccess(res)) {
              this.$message.success(res.message);
              this.handleCancel();
            }
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      } else {
        if (isSubmit) {
          addFreightService(this.freightBillDTOList).then((res) => {
            this.submitLoading = true;
            if (isResponseSuccess(res)) {
              this.$message.success(res.message);
              this.handleCancel();
            }
          }).catch(() => {
            this.submitLoading = false;
          });
        } else {
          stashAddFreightService(this.freightBillDTOList).then((res) => {
            this.submitLoading = true;
            if (isResponseSuccess(res)) {
              this.$message.success(res.message);
              this.handleCancel();
            }
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      }
    }
  },
};
</script>
<style scoped>
.page-footer {
  margin-top: 10px;
}
</style>
